package com.authenticateCenter.domain.entity;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

import com.authenticateCenter.domain.Checker;
import com.authenticateCenter.mapper.RoleAuthorityMapper;
import com.authenticateCenter.mapper.RoleMapper;
import com.authenticateCenter.service.IRoleService;
import com.authenticateCenter.util.MybatisUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.*;
import org.springframework.util.Assert;

/**
 * <p>
 * 
 * </p>
 *
 * @author 大忽悠
 * @since 2022年10月08日
 */
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("role")
public class Role implements Serializable, Checker<Role> {

    private static final long serialVersionUID = 1L;
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String name;

    private String nameZh;

    private Integer level;

    private Integer enabled;

    public static void existCheckOfIdList(List<Integer> roleIdList, RoleMapper roleMapper) {
        boolean exists = roleMapper.exists(new QueryWrapper<Role>()
                .in("id", roleIdList));
        if(!exists){
            throw new IllegalArgumentException("角色列表集合中,存在错误的角色id: "+roleIdList);
        }
    }

    public static void repeatReleaseCheck(Integer roleId, List<Integer> authorityIdList, RoleAuthorityMapper roleAuthorityMapper) {
        boolean exists = roleAuthorityMapper.exists(new QueryWrapper<RoleAuthority>()
                .eq("rid", roleId)
                .in("aid", authorityIdList));
        if(exists){
            throw new IllegalArgumentException("当前角色已经具备权限列表"+authorityIdList+"中某个权限,请重新检查后再赋权");
        }
    }

    public static List<String> filterWrongRoleName(List<String> roleNameList, RoleMapper roleMapper) {
        return roleNameList.stream().filter(roleName-> roleMapper.exists(new QueryWrapper<Role>().eq("name",roleName))).collect(Collectors.toList());
    }

    public static List<Integer> mapRoleNameListToRoleIdList(List<String> rightRoleNameList, RoleMapper roleMapper) {
         return rightRoleNameList.stream().map(roleName-> roleMapper.selectOne(new QueryWrapper<Role>().eq("name",roleName)).getId())
                 .collect(Collectors.toList());
    }

    public static void existCheckOfNameList(List<String> roleNameList, RoleMapper roleMapper) {
        boolean exists = roleMapper.exists(new QueryWrapper<Role>()
                .in("name", roleNameList));
        if(!exists){
            throw new IllegalArgumentException("角色列表集合中,存在错误的角色name: "+roleNameList);
        }
    }


    @Override
    public void insertCheck(IService<Role> iService) {
        MybatisUtil.repeatCheck(iService,"name",name,"已经存在名为: "+name+"的角色了");
    }
}
